/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Controlers.Admin;

import Pojos.DanhMucSanPham;
import Pojos.SanPham;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

/**
 *
 * @author ToanNhan
 */
@WebServlet(name = "QuanLySanPhamControler", urlPatterns = {"/Admin/QuanLySanPhamControler"})
public class QuanLySanPhamControler extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");

        try {
            String command = request.getParameter("command");
            if (command == null || command.length() == 0) {
                response.sendRedirect("/WebsiteBanHang/Admin/QuanLySanPham.jsp");
            } else {
                String action = request.getParameter("action");
                if (action != null){
                    if (action.compareTo("hetHang") == 0){
                        setTinhTrangSanPham(request, response, SanPham.HET_HANG);
                    }
                    if (action.compareTo("conHang") == 0){
                        setTinhTrangSanPham(request, response, SanPham.CON_HANG);
                    }
                    if (action.compareTo("editDetail") == 0){
                        String maSanPham = request.getParameter("chkMaSanPham");
                        response.sendRedirect("/WebsiteBanHang/Admin/CapNhatThongTinSanPham.jsp?maSanPham=" + maSanPham);
                      
                    }
                }
                command = command.toLowerCase();
                if (command.compareTo("laydanhsachsanpham") == 0) {
                    layDanhSachSanPham(request, response);
                }
                if (command.compareTo("laydanhsachdanhmuc") == 0) {
                    layDanhSachDanhMuc(request, response);
                }               
            }
        } finally {
        }
    }

    protected void setTinhTrangSanPham(HttpServletRequest request, HttpServletResponse response, int tinhTrang){
        String[] arrMaSanPham = request.getParameterValues("chkMaSanPham");
        SessionFactory factory = new Configuration().configure("Pojos/hibernate.cfg.xml").buildSessionFactory();
        Session session = factory.openSession();
        session.beginTransaction();
        Query query = session.createQuery("From SanPham Where TinhTrang<>?");
        query.setInteger(0, tinhTrang);
        List<SanPham> lstSanPham = query.list();
        for (String maSanPham : arrMaSanPham){
            for (int i = 0; i < lstSanPham.size(); i++){
                if (lstSanPham.get(i).getMaSanPham().compareTo(maSanPham) == 0){
                    lstSanPham.get(i).setTinhTrang(tinhTrang);
                    session.save(lstSanPham.get(i));
                }
            }
        }
        session.getTransaction().commit();
        session.close();
    }

    protected void layDanhSachSanPham(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String maDanhMuc = request.getParameter("maDanhMuc");
        if (maDanhMuc == null) {
            maDanhMuc = "DM01";
        }
        int trangHienTai = 1;
        if (request.getParameter("trangHienTai") != null) {
            trangHienTai = Integer.valueOf(request.getParameter("trangHienTai"));
        }
        int soLuongTrenTrang = 20;
        if (request.getParameter("soLuongTrenTrang") != null) {
            soLuongTrenTrang = Integer.valueOf(request.getParameter("soLuongTrenTrang"));
        }
        SessionFactory factory = new Configuration().configure("Pojos/hibernate.cfg.xml").buildSessionFactory();
        Session session = factory.openSession();
        Query query = session.createQuery("From SanPham Where danhMucSanPham.maDanhMuc = ?");
        query.setString(0, maDanhMuc);

        List<SanPham> lstSanPham = (List<SanPham>) query.list();
        int tongSoLuong = lstSanPham.size();
        if (tongSoLuong > 0) {
            int beginIndex = (trangHienTai - 1) * soLuongTrenTrang;
            int endIndex = beginIndex + soLuongTrenTrang;
            if (endIndex < tongSoLuong) {
                lstSanPham = lstSanPham.subList(beginIndex, endIndex);
            } else {
                lstSanPham = lstSanPham.subList(beginIndex, tongSoLuong - 1);
            }
            int tongSoTrang = tongSoLuong / soLuongTrenTrang;
            if (tongSoLuong % soLuongTrenTrang != 0) {
                tongSoTrang++;
            }

            request.setAttribute("tongSoTrang", tongSoTrang);
        }
        request.setAttribute("danhSachSanPham", lstSanPham);
        session.close();
        request.getRequestDispatcher("QuanLySanPham.jsp").forward(request, response);
    }

    protected void layDanhSachDanhMuc(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        SessionFactory factory = new Configuration().configure("Pojos/hibernate.cfg.xml").buildSessionFactory();
        Session session = factory.openSession();
        Query query = session.createQuery("From DanhMucSanPham");
        List<DanhMucSanPham> lstDanhMucSanPham = (List<DanhMucSanPham>) query.list();
        request.setAttribute("danhSachDanhMuc", lstDanhMucSanPham);
        session.close();
        request.getRequestDispatcher("QuanLySanPham.jsp").forward(request, response);
    }
    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">

    /**
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
